'''
Created on Oct 8, 2012

@author: peng
'''
import os
import MySQLdb


BELUGA_DB_CONFIG = {'host': '10.42.133.171',
                    'user': 'dev_api',
                    'password': 'api_dev_pwd',
                    'db': 'beluga_api',
                    'port': 3306}


class MySQLdbWrapper:

    conn = None

    def connect(self):
        self.conn = MySQLdb.connect(host=BELUGA_DB_CONFIG['host'],
                                    user=BELUGA_DB_CONFIG['user'],
                                    passwd=BELUGA_DB_CONFIG['password'],
                                    db=BELUGA_DB_CONFIG['db'],
                                    port=BELUGA_DB_CONFIG['port'])
        self.conn.set_character_set('utf8')
        self.conn.autocommit(True)

    def cursor(self):
        try:
            self.connect()
            return self.conn.cursor()
        except MySQLdb.OperationalError:
            self.connect()
            return self.conn.cursor()

_db = MySQLdbWrapper()


def get_data(sql):
    try:
        cursor = _db.cursor()
        cursor.execute(sql)
        data = cursor.fetchall()
        return data
    finally:
        cursor.close()

path = '/mnt/export/user-data'

# user daily
sql_0 = \
'''
select app_key, date, promotion_id, app_version, channel, total_count
from user_daily
where date<'2012-10-01'
'''


def remove_control_characters(line):
    # mpa = dict.fromkeys(range(32))
    # line = line.translate(mpa)
    return line


def flush(data_list):
    if len(data_list) == 0:
        return
    f = open(os.path.join(path, 'total_user_data'), 'a+')
    data = '\n'.join(data_list)
    f.write(data)
    f.write('\n')
    f.close()


def export_summary():
    data_list = []
    rows = get_data(sql_0)
    for row in rows:
        line = '\t'.join([row[0], str(row[1])[:10].replace('-', ''), row[2], row[3], row[4], \
                          '0', '-', str(row[5])])
        data_list.append(remove_control_characters(line))
    flush(data_list)


if __name__ == '__main__':
    export_summary()
    print 'summary done'
